import { resolve } from 'path'
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
import vue from '@vitejs/plugin-vue'
import * as path from 'path'
import fs from 'fs'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import UnoCSS from 'unocss/vite'
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig(({ mode, command }) => {
  console.log('defineConfig', mode, command)

  // 解决开发环境vite 构建时optimized dependencies changed. reloading 问题
  //   componentsDir 是 Element Plus 组件目录的路径。
  // 使用 fs.readdirSync 同步读取该目录下的所有子目录（即组件名）
  const optimizeDepsElementPlusIncludes = ['element-plus/es', '@vuemap/vue-amap/es']

  // 使用同步方法读取目录和检查文件
  const componentsDir = 'node_modules/element-plus/es/components'
  const componentDirs = fs.readdirSync(componentsDir)

  componentDirs.forEach((dirname) => {
    const stylePath = path.join(componentsDir, dirname, 'style/index.mjs')
    if (fs.existsSync(stylePath)) {
      optimizeDepsElementPlusIncludes.push(`element-plus/es/components/${dirname}/style/index`)
      optimizeDepsElementPlusIncludes.push(` element-plus/es/components/table-v2/style/css`)
    }
  })
  return {
    main: {
      plugins: [externalizeDepsPlugin()]
    },
    preload: {
      plugins: [externalizeDepsPlugin()]
    },
    renderer: {
      resolve: {
        alias: {
          '@renderer': resolve('src/renderer/src')
        }
      },
      plugins: [
        vue(),
        vueJsx(),
        AutoImport({
          // 自动导入 Vue 相关函数，如：ref, reactive, toRef 等
          imports: ['vue'],
          resolvers: [ElementPlusResolver()]

          // dts: resolve(pathSrc, 'types', 'auto-imports.d.ts') // 指定自动导入函数TS类型声明文件路径
        }),
        Components({
          resolvers: [ElementPlusResolver()]
          // dts: resolve(pathSrc, 'types', 'components.d.ts') // 指定自动导入组件TS类型声明文件路径
        }),
        createSvgIconsPlugin({
          // 指定需要缓存的图标文件夹
          iconDirs: [resolve(process.cwd(), 'src/renderer/src/icons')],
          // 指定symbolId格式
          symbolId: 'icon-[dir]-[name]'
        }),
        UnoCSS({
          /* options */
        })
      ]
    }
  }
})
// export default defineConfig({

// })
